#include "TimeStamp.h"
#include <sys/time.h>

TimeStamp::TimeStamp()
    : _microSecondsSinceEpoch(0)
{
}
TimeStamp::TimeStamp(int64_t microSecondsSinceEpochArg)
    : _microSecondsSinceEpoch(microSecondsSinceEpochArg)
{
}
TimeStamp TimeStamp::now()
{
    struct timeval tv;
    gettimeofday(&tv, nullptr); // 获取秒和微秒
    return TimeStamp(tv.tv_sec * kMicroSecondsPerSecond + tv.tv_usec);
}

string TimeStamp::toString() const
{
    char buf[128] = {0};
    time_t seconds = static_cast<time_t>(_microSecondsSinceEpoch);
    struct tm tm_time;
    localtime_r(&seconds, &tm_time);
    snprintf(buf, 128, "%4d-%02d-%02d %02d:%02d:%02d",
             tm_time.tm_year + 1900,
             tm_time.tm_mon + 1,
             tm_time.tm_mday,
             tm_time.tm_hour,
             tm_time.tm_min,
             tm_time.tm_sec);
    return buf;
}

string TimeStamp::toFormattedString(bool showMicroseconds) const
{
    char buf[64] = {0};
    time_t seconds = static_cast<time_t>(_microSecondsSinceEpoch / kMicroSecondsPerSecond);
    struct tm tm_time;
    localtime_r(&seconds, &tm_time);

    if (showMicroseconds)
    {
        int microseconds = static_cast<int>(_microSecondsSinceEpoch % kMicroSecondsPerSecond);
        snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d.%06d",
                tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
                tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec,
                microseconds);
    }
    else
    {
        snprintf(buf, sizeof(buf), "%4d%02d%02d %02d:%02d:%02d",
                tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
                tm_time.tm_hour, tm_time.tm_min, tm_time.tm_sec);
    }
    return buf;
}